package services

import (
	"fmt"
	"nonius/forms"
	"nonius/model"

	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
)

func GetUser(id int64) *model.User {
	user := &model.User{
		ID: id,
	}
	ormer := orm.NewOrm()
	if err := ormer.Read(user); err == nil {
		return user
	}
	return nil
}

func GetUsers() []*model.User {
	// ormer := config.UserOrmer
	ormer := orm.NewOrm()

	queryset := ormer.QueryTable(&model.User{})
	var users []*model.User
	queryset.All(&users)
	return users

}

func AddUser(name, password, addr string, sex bool) {
	hash, _ := bcrypt.GenerateFromPassword([]byte(password), 5)
	user := model.User{
		Name:     name,
		Password: string(hash),
		Addr:     addr,
		Sex:      sex,
	}
	ormer := orm.NewOrm()
	ormer.Insert(&user)
}

func EditUser(id int64, name, addr string, sex bool) {
	user := &model.User{
		ID: id,
	}
	ormer := orm.NewOrm()
	ormer.Read(user)

	user.Name = name
	user.Addr = addr
	user.Sex = sex
	ormer.Update(user)
}

func DelUser(id int64) {

	ormer := orm.NewOrm()
	ormer.Delete(&model.User{ID: id})

}

func GetUserByName(name string) *model.User {
	ormer := orm.NewOrm()
	user := &model.User{
		Name: name,
	}
	if err := ormer.Read(user, "Name"); err == nil {
		return user
	}
	return nil

}

func Auth(form *forms.LoginForm) *model.User {
	if user := GetUserByName(form.Username); user == nil {
		fmt.Println(user, "aaa")
		// 用户名密码错误
		return nil
	} else {
		if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.Password)); err == nil {
			return user
		} else {
			// 用户名密码错误
			return nil
		}
	}

}
